package com.antler.smt.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 枚举工具类
 *
 * @author vic
 * @date 2017-11-28 17:34
 */
public class EnumUtil {

    /**
     * 使用枚举类型对应的typeCode获取枚举类型
     *
     * @param clazz  枚举类的class
     * @param getTypeCodeMethodName 传入的typeCode的get方法
     * @param typeCode  传入的typeCode值，这个方法为Integer类型
     * @return
     */
    public static <T extends Enum<T>> T getEnumByTypeCode(Class<T> clazz, String getTypeCodeMethodName, Integer typeCode) {
        T result = null;
        try {
            T[] arr = clazz.getEnumConstants();
            Method targetMethod = clazz.getDeclaredMethod(getTypeCodeMethodName);
            Integer typeCodeVal = null;
            for (T entity : arr) {
                typeCodeVal = Integer.valueOf(targetMethod.invoke(entity).toString());
                if (typeCodeVal.equals(typeCode)) {
                    result = entity;
                    break;
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 使用枚举类型对应的typeName获取枚举类型
     *
     * @param clazz  枚举类的class
     * @param getTypeNameMethodName 传入的typeName的get方法
     * @param typeName  传入的typeName值，这个方法为String类型
     * @return
     */
    public static <T extends Enum<T>> T getEnumByTypeName(Class<T> clazz, String getTypeNameMethodName, String typeName) {
        T result = null;
        try {
            T[] arr = clazz.getEnumConstants();
            Method targetMethod = clazz.getDeclaredMethod(getTypeNameMethodName);
            String typeNameVal = null;
            for (T entity : arr) {
                typeNameVal = targetMethod.invoke(entity).toString();
                if (typeNameVal.contentEquals(typeName)) {
                    result = entity;
                    break;
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return result;
    }
}
